const net = require('net');

var clients = [];

const server = net.createServer((c)=>{
    
	c.on('error',(e)=>{
	   	console.log(e.toString());
	});
});

server.on('connection',(socket)=>{
    initSocksConnection(socket);
});

function initSocksConnection(socket) {
     clients.push(socket);
     
     socket.on('end',function(){
     	var idx = clients.indexOf(this);
     	if(idx != -1){
     	   clients.splice(idx,1);
     	}
     });
     
     var client = '';
     socket.on('data',function(data){
		 if(data[0] == 5){
		     
		 	 if(data[3] && data[3] == 1){   //IPV4 find ip and port
		 	      
		 	 	  var addr = parseInt(data[4],10)+'.'+parseInt(data[5],10)+'.'+parseInt(data[6],10)+'.'+parseInt(data[7],10);
		 	 	  var port = (parseInt(data[8],10) * 256) + parseInt(data[9],10)
		 	 	  //console.log(addr+':'+port);
		 	 	  var buffer = new Buffer([0x05,0x00,0x00,0x01]);
		 	 	  var replay = Buffer.concat([buffer,new Buffer([data[4],data[5],data[6],data[7],data[8],data[9]])],10);
		 	 	  
		 	 	  socket.write(replay);
		 	 	  
		 	 	  client = net.connect({host:addr,port: port}, () => {
		 	 	        console.log('启动代理中..');
                  });
                  
                  console.log(client);
		 	 	  
		 	 	  client.on('data',function(data){
		                 socket.write(data);    
		          });
		          
		          client.on('error',(e)=>{});
		 	 }else if(data[3] && data[3] == 3){  //Domain name
		 	 	  console.log('待处理..');
		 	 }else {
		 	 	const buf = new Buffer([0x05,0x00]);  //version成功
		 	    socket.write(buf);
		 	 }
		 	 
		 }else {   //发送请求开始
		      if(client){
		          client.write(data);
		      }
		 }
	});
     
     
}

server.listen(8088,()=>{
	console.log('开始服务...');
});